package com.ai.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author zhuangwei
 * @Date 2020/11/26
 */
@RestControllerAdvice
public class GlobalWebException {

    /**
     * 前端参数异常时，返回 验证层中声明的错误信息
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException ex) {
        Map<String, Object> result = new HashMap<String, Object>(3);

        List<FieldError> errors = ex.getBindingResult().getFieldErrors();//得到所有的参数异常
        //String message = errors.get(0).getDefaultMessage();
        //int count= ex.getBindingResult().getErrorCount();//得到异常参数的个数
        result.put("code", -1);
        result.put("msg", errors.get(0).getDefaultMessage()); // 返回第一个异常参数信息
        return new ResponseEntity(result, HttpStatus.BAD_REQUEST);
    }

    /**
     * 运行时异常 用于处理 RuntimeException 异常
     */
    @ExceptionHandler(value = {RuntimeException.class})
    public ResponseEntity<Object> handleBindException(RuntimeException ex) {
        System.out.println(ex.getClass());
        System.out.println(ex.getMessage());
        Map<String, Object> result = new HashMap<String, Object>(2);
        result.put("code", -2);
        result.put("msg", ex.getMessage());
        return new ResponseEntity(result, HttpStatus.EXPECTATION_FAILED);
    }

    /**
     * 系统产生的未知 异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    ResponseEntity exception(Exception ex) {
        Map<String, Object> result = new HashMap<String, Object>(3);
        result.put("code", -3);
        result.put("msg", ex.getMessage());
        result.put("data", null);
        System.out.println("系统异常...");
        return new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
